package cn.itcast.music.helper;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import androidx.annotation.Nullable;
import cn.itcast.music.entity.Music;
import cn.itcast.music.entity.MusicHistory;
import java.util.ArrayList;
import java.util.List;

@SuppressLint("Range")
public class HistoryHelper extends BaseHelper {

    private final MusicHelper musicHelper;

    public HistoryHelper(@Nullable Context context) {
        super(context);
        musicHelper = new MusicHelper(context);
    }

    public void insert(MusicHistory musicHistory) {
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("INSERT INTO history (dateTime, musicId) VALUES (?, ?)",
                new Object[]{musicHistory.getDateTime(),
                        musicHistory.getMusic().getId()});
        db.close();
    }

    public void deleteAll() {
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("DELETE FROM history");
        db.close();
        musicHelper.deleteAll();
    }

    public List<MusicHistory> selectAll() {
        SQLiteDatabase db = getReadableDatabase();
        List<MusicHistory> historyList = new ArrayList<>();
        try (Cursor cursor = db.rawQuery("SELECT * FROM history", null)) {
            while (cursor.moveToNext()) {
                int id = cursor.getInt(cursor.getColumnIndex("id"));
                String dateTime = cursor.getString(
                        cursor.getColumnIndex("dateTime"));
                int musicId = cursor.getInt(cursor.getColumnIndex("musicId"));
                Music music = musicHelper.selectById(musicId);
                historyList.add(new MusicHistory(id, dateTime, music));
            }
        }
        return historyList;
    }

}
